"""
文档处理主程序
整合PDF内容提取和文档转换功能
"""

import os
from typing import List, Dict, Any
from main import extract_content_all
from document_converter import SimpleDocumentConverter, convert_document_to_markdown

class DocumentProcessor:
    """统一的文档处理器，支持PDF和Word文档"""
    
    def __init__(self):
        self.pdf_extractor = None  # 使用main.py中的extract_content_all
        self.doc_converter = SimpleDocumentConverter()
        
    def process_file(self, file_path: str, output_dir: str = "./file_output") -> Dict[str, Any]:
        """
        处理单个文件，支持PDF和Word格式
        
        Args:
            file_path (str): 输入文件路径
            output_dir (str): 输出目录
            
        Returns:
            Dict[str, Any]: 处理结果信息
        """
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"文件不存在: {file_path}")
        
        file_ext = os.path.splitext(file_path)[1].lower()
        filename = os.path.splitext(os.path.basename(file_path))[0]
        
        # 确保输出目录存在
        os.makedirs(output_dir, exist_ok=True)
        
        result = {
            "input_file": file_path,
            "file_type": file_ext,
            "filename": filename,
            "success": False,
            "outputs": [],
            "error": None
        }
        
        try:
            if file_ext == '.pdf':
                result.update(self._process_pdf(file_path, output_dir, filename))
            elif file_ext in ['.docx', '.doc']:
                result.update(self._process_word(file_path, output_dir, filename))
            else:
                raise ValueError(f"不支持的文件格式: {file_ext}")
                
            result["success"] = True
            
        except Exception as e:
            result["error"] = str(e)
            print(f"❌ 处理文件失败 {file_path}: {e}")
        
        return result
    
    def _process_pdf(self, file_path: str, output_dir: str, filename: str) -> Dict[str, Any]:
        """处理PDF文件"""
        outputs = []
        
        # 方法1: 使用extract_content_all进行详细提取（保留表格合并功能）
        try:
            txt_output = os.path.join(output_dir, f"{filename}_detailed.txt")
            extract_content_all(file_path, txt_output)
            outputs.append({"type": "detailed_txt", "path": txt_output})
            print(f"✅ PDF详细提取完成: {txt_output}")
        except Exception as e:
            print(f"⚠️ PDF详细提取失败: {e}")
        
        # 方法2: 使用文档转换器转换为Markdown
        try:
            md_output = os.path.join(output_dir, f"{filename}_markdown.md")
            convert_document_to_markdown(file_path, md_output)
            outputs.append({"type": "markdown", "path": md_output})
            print(f"✅ PDF转Markdown完成: {md_output}")
        except Exception as e:
            print(f"⚠️ PDF转Markdown失败: {e}")
        
        return {
            "processing_methods": ["detailed_extraction", "markdown_conversion"],
            "outputs": outputs
        }
    
    def _process_word(self, file_path: str, output_dir: str, filename: str) -> Dict[str, Any]:
        """处理Word文件"""
        outputs = []
        
        # Word文档转换为Markdown
        try:
            md_output = os.path.join(output_dir, f"{filename}_markdown.md")
            convert_document_to_markdown(file_path, md_output)
            outputs.append({"type": "markdown", "path": md_output})
            print(f"✅ Word转Markdown完成: {md_output}")
        except Exception as e:
            print(f"⚠️ Word转Markdown失败: {e}")
            raise e
        
        return {
            "processing_methods": ["markdown_conversion"],
            "outputs": outputs
        }
    
    def process_directory(self, input_dir: str, output_dir: str = "./file_output") -> List[Dict[str, Any]]:
        """
        批量处理目录中的所有支持的文档
        
        Args:
            input_dir (str): 输入目录
            output_dir (str): 输出目录
            
        Returns:
            List[Dict[str, Any]]: 所有文件的处理结果
        """
        if not os.path.exists(input_dir):
            raise FileNotFoundError(f"输入目录不存在: {input_dir}")
        
        supported_extensions = ['.pdf', '.docx', '.doc']
        results = []
        
        print(f"🚀 开始批量处理目录: {input_dir}")
        
        for filename in os.listdir(input_dir):
            file_path = os.path.join(input_dir, filename)
            
            if os.path.isfile(file_path):
                file_ext = os.path.splitext(filename)[1].lower()
                
                if file_ext in supported_extensions:
                    print(f"\n📄 处理文件: {filename}")
                    result = self.process_file(file_path, output_dir)
                    results.append(result)
                else:
                    print(f"⏭️ 跳过不支持的文件: {filename}")
        
        # 生成处理报告
        self._generate_report(results, output_dir)
        
        return results
    
    def _generate_report(self, results: List[Dict[str, Any]], output_dir: str):
        """生成处理报告"""
        report_path = os.path.join(output_dir, "processing_report.txt")
        
        success_count = sum(1 for r in results if r["success"])
        failed_count = len(results) - success_count
        
        with open(report_path, 'w', encoding='utf-8') as f:
            f.write("文档处理报告\n")
            f.write("=" * 50 + "\n\n")
            f.write(f"总文件数: {len(results)}\n")
            f.write(f"成功处理: {success_count}\n")
            f.write(f"处理失败: {failed_count}\n\n")
            
            f.write("详细结果:\n")
            f.write("-" * 30 + "\n")
            
            for i, result in enumerate(results, 1):
                f.write(f"\n{i}. {result['filename']}{result['file_type']}\n")
                if result["success"]:
                    f.write(f"   状态: ✅ 成功\n")
                    f.write(f"   处理方法: {', '.join(result.get('processing_methods', []))}\n")
                    for output in result.get('outputs', []):
                        f.write(f"   输出: {output['type']} -> {output['path']}\n")
                else:
                    f.write(f"   状态: ❌ 失败\n")
                    f.write(f"   错误: {result.get('error', '未知错误')}\n")
        
        print(f"\n📊 处理报告已生成: {report_path}")
        print(f"总结: 成功 {success_count}/{len(results)} 个文件")


def main():
    """主函数示例"""
    processor = DocumentProcessor()
    
    # 处理单个文件示例
    test_file = "./file_input/test.pdf"
    if os.path.exists(test_file):
        print("=== 单文件处理示例 ===")
        result = processor.process_file(test_file)
        print(f"处理结果: {result['success']}")
    
    # 批量处理示例
    input_directory = "./file_input"
    if os.path.exists(input_directory):
        print("\n=== 批量处理示例 ===")
        results = processor.process_directory(input_directory)
        print(f"批量处理完成，共处理 {len(results)} 个文件")


if __name__ == "__main__":
    main()
